//
//  UserViewController.swift
//  worldexchange
//
//  Created by xionghao on 2019/1/8.
//  Copyright © 2019 xionghao. All rights reserved.
//

import UIKit
import RxSwift

class UserViewController: QMUICommonViewController {
    
    let dispose = DisposeBag()
    var enableTrace = false
    
    @IBOutlet weak var tableView: UITableView!
    var userCellItems:[UserCellItem] = [UserCellItem]()
    override func viewDidLoad() {
        super.viewDidLoad()
        
      
        self.setupHeaderView()
        self.setupView()
        NotificationCenter.default.addObserver(self, selector: #selector(refreshView), name: NSNotification.Name.init(rawValue: "UserLoginChange"), object: nil)
          self.loadData()
        // Do any additional setup after loading the view.
    }
    
    lazy var userNoLoginHeader:UserHeaderView = UserHeaderView.loadView()
    
    lazy var userLoginHeader:UserLoginHeader = UserLoginHeader.loadView()
    
    var footerView:UIView!
    
    func setupHeaderView() {
        
        self.tableView.rowHeight = 50
        self.tableView.register(UINib(nibName: "UserViewCell", bundle: nil), forCellReuseIdentifier: "cell-item")
        setupFooterView()
        self.refreshView()
    }
    
    
    func loadData()  {
        provider.rx.request(WE.setting()).filterSuccessfulStatusCodes().mapJSON().subscribe(onSuccess: { (result) in
            if let data = result as? [String:Any] {
                if let enable_trace = data["enable_trace"] as? Bool {
                    self.enableTrace = enable_trace
                    self.setupView()
                }
                if let email  = data["email"] as? String  {
                    appEmail = email
                }
                
                if let username  = data["username"] as? String  {
                    appThirdUser = username
                }
               
            }
        }) { (error) in
            print(error)
            }.disposed(by: dispose)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func refreshView() {
        self.tableView.tableHeaderView = isLogin ? userLoginHeader : userNoLoginHeader
        self.tableView.tableHeaderView?.layoutIfNeeded()
        self.tableView.tableHeaderView = isLogin ? userLoginHeader : userNoLoginHeader
        userLoginHeader.userName.text = userData?.username
        userLoginHeader.email.text = userData?.email
        self.tableView.tableHeaderView?.qmui_height = 180
        if isLogin {
            self.tableView.tableFooterView = self.footerView
        }else {
            self.tableView.tableFooterView = nil
        }
    }
    
    
    func setupFooterView() {
        let screenWidth = UIScreen.main.bounds.width
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height:  120))
        let addBtn = QMUIFillButton(fill: UIColor.qmui_color(withHexString: "#ff3300"), titleTextColor: UIColor.white)
        addBtn.setTitle(LanguageHelper.getString(key: "LogoutLabel"), for: UIControl.State.normal)
        footerView.addSubview(addBtn)
        addBtn.snp.makeConstraints { (maker) in
            maker.left.equalTo(footerView.snp.left).offset(16)
            maker.right.equalTo(footerView.snp.right).offset(-16)
            maker.height.equalTo(44)
            maker.centerY.equalToSuperview()
        }
        addBtn.cornerRadius = 5
        addBtn.addTarget(self, action: #selector(logoutClick), for: UIControl.Event.touchUpInside)
        self.footerView = footerView
    }
    
    @objc func logoutClick()  {
        let alertVC = QMUIAlertController(title: LanguageHelper.getString(key: "LogoutAlert"), message: nil, preferredStyle: QMUIAlertControllerStyle.alert)
        alertVC.addAction(QMUIAlertAction(title: LanguageHelper.getString(key: "BtnOK"), style: QMUIAlertActionStyle.destructive, handler: { (_, _) in
            Utils.logout()
            
        }))
        alertVC.addAction(QMUIAlertAction(title: LanguageHelper.getString(key: "BtnCancel"), style: QMUIAlertActionStyle.cancel, handler: { (_, _) in
            
        }))
        alertVC.showWith(animated: true)
        
        
    }
    
    
    func setupView() {
        
        userCellItems.removeAll()
        
        let my = UserCellItem()
        my.name = LanguageHelper.getString(key: "appointLabel")
        my.icon = #imageLiteral(resourceName: "icon_appoint")
        my.action = {
            if !isLogin {
                Utils.pushLogin()
            }else {
                let vc = UserAppoitmentViewController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        userCellItems.append(my)
        
        let message = UserCellItem()
        message.name = LanguageHelper.getString(key: "短消息")
        message.icon = #imageLiteral(resourceName: "icon_message")
        message.action = {
            if !isLogin {
                Utils.pushLogin()
            }else {
                let vc = UserMessageViewController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        userCellItems.append(message)
        
        
        let about = UserCellItem()
        about.name = LanguageHelper.getString(key: "aboutLabel")
        about.icon = #imageLiteral(resourceName: "icon_about")
        about.action = {
           let vc = AboutViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        userCellItems.append(about)
        
        let process = UserCellItem()
        process.name = LanguageHelper.getString(key: "TabRemittance")
        process.icon = #imageLiteral(resourceName: "icon_process")
        process.action = {
            let vc = WebViewController()
            vc.articleItem = processItem
            vc.type = 1
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
        if enableTrace {
            userCellItems.append(process)
        }
        
        let promotion = UserCellItem()
        
        promotion.name = LanguageHelper.getString(key: "TabPromotion")
        promotion.icon = #imageLiteral(resourceName: "icon_promotion")
        promotion.action = {
            let vc = PromotionViewController()
           
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        userCellItems.append(promotion);
        
        let lang = UserCellItem()
        lang.name = LanguageHelper.getString(key: "LangLabel")
        lang.icon = #imageLiteral(resourceName: "icon_lang")
        lang.action = {
            let vc = LangViewController()
            //            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        userCellItems.append(lang)
        
        let currency = UserCellItem()
        currency.name = LanguageHelper.getString(key: "currencyLabel")
        currency.icon = #imageLiteral(resourceName: "icon_currency")
        currency.rightIcon = defaultCurrency == "THB" ? #imageLiteral(resourceName: "icon_thd") : #imageLiteral(resourceName: "icon_hkd")
        userCellItems.append(currency)
        currency.action = {
//            self.showChangeCurrency()
        }
        
        
        self.tableView.reloadData()
        
        
    }
    
    func changeCurrency(_ currency:String) {
        defaultCurrency = currency
        let currency = userCellItems[4]
        currency.rightIcon = defaultCurrency == "THB" ? #imageLiteral(resourceName: "icon_thd") : #imageLiteral(resourceName: "icon_hkd")
        userCellItems[4] = currency
        self.tableView.reloadData()
        NotificationCenter.default.post(Notification.init(name: Notification.Name.init(rawValue: changeCurrencyNoticeName)))
    }
    
    func showChangeCurrency() {
//        let changeVc =   QMUIAlertController(title: LanguageHelper.getString(key: "changeCurrencyLabel"), message: nil, preferredStyle: QMUIAlertControllerStyle.actionSheet)
//        changeVc.addAction(QMUIAlertAction(title: "THB", style: QMUIAlertActionStyle.default, handler: { (_, _) in
//            self.changeCurrency("THB")
//        }))
//        changeVc.addAction(QMUIAlertAction(title: "HKD", style: QMUIAlertActionStyle.default, handler: { (_, _) in
//            self.changeCurrency("HKD")
//        }))
//        changeVc.addAction(QMUIAlertAction(title: LanguageHelper.getString(key: "BtnCancel"), style: QMUIAlertActionStyle.cancel, handler: { (_, _) in
//
//        }))
//        changeVc.showWith(animated: true)
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}

extension UserViewController:QMUITableViewDelegate,QMUITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userCellItems.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = userCellItems[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell-item") as! UserViewCell
        cell.icon.image = item.icon
        cell.title.text = item.name
        cell.rightImage.image = item.rightIcon
        if item.rightIcon != nil {
            cell.accessoryType = .none
            cell.rightImage.isHidden = false
        }else {
            cell.accessoryType = .disclosureIndicator
            cell.rightImage.isHidden = true
            
        }
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let action = userCellItems[indexPath.row]
        if action.action != nil {
            action.action!()
        }
//        if indexPath.row == 4 {
//            let vc = LangViewController()
//            //            vc.hidesBottomBarWhenPushed = true
//            self.navigationController?.pushViewController(vc, animated: true)
//        }else if indexPath.row == 3 {
//            let vc = WebViewController()
//            vc.articleItem = aboutItem
//            vc.type = 1
//            vc.hidesBottomBarWhenPushed = true
//            self.navigationController?.pushViewController(vc, animated: true)
//        }else if indexPath.row == 2 {
//            let vc = WebViewController()
//            vc.type = 1
//            vc.articleItem = processItem
//            vc.hidesBottomBarWhenPushed = true
//            self.navigationController?.pushViewController(vc, animated: true)
//        }else if indexPath.row == 5 {
//            self.showChangeCurrency()
//        }else if indexPath.row == 0 {
//            if !isLogin {
//                Utils.pushLogin()
//            }else {
//                let vc = UserAppoitmentViewController()
//                vc.hidesBottomBarWhenPushed = true
//                self.navigationController?.pushViewController(vc, animated: true)
//            }
//
//        }
//        else if indexPath.row == 1 {
//            if !isLogin {
//                Utils.pushLogin()
//            }else {
//                let vc = UserMessageViewController()
//                vc.hidesBottomBarWhenPushed = true
//                self.navigationController?.pushViewController(vc, animated: true)
//            }
//
//        }
    }
    
}
